import type { Request } from 'express'
import { todoService } from '@server/services/todo-service'
import { ApiResponse } from '@data/api'
import { NotFoundError } from '@server/error/errors'

export default async function toggleTodo(request: Request) {
  const id = request.params.id

  const existing = await todoService.getTodoById(id)
  if (!existing) {
    throw new NotFoundError('Todo not found')
  }

  const todo = await todoService.updateTodo(id, {
    completed: !existing.completed,
  })

  const response: ApiResponse = {
    success: true,
    data: todo,
    message: `Todo ${todo?.completed ? 'completed' : 'uncompleted'}`,
  }

  return response
}
